<template>
  <div class="flow-box">
    <el-table
        :data="tableData"
        stripe
        style="width: 100%;height: 91vh;"
        border
        max-height="91vh"
        empty-text="暂无数据"
    >
      <el-table-column
          fixed
          prop="approve_id"
          label="ID"
          width="200"
          align="center"
      />
      <el-table-column
          label="申请人"
          width="100"
          align="center"
      >
        {{userInfo.username}}
      </el-table-column>
      <el-table-column
          label="申请时间"
          width="120  "
          align="center"
      >
        <template #default="{row}">
          {{computeDate(row.created_at)}}
        </template>
      </el-table-column>
      <el-table-column
          label="状态"
          align="center"
          width="120"
      >
        <template #default="{row}">
          <el-tag type="info" v-if="row.status === 0">已提交</el-tag>
          <el-tag type="warning" v-else-if="row.status === 1">审批中</el-tag>
          <el-tag type="warning" v-else-if="row.status === 2">已完成</el-tag>
          <el-tag type="info" v-else-if="row.status === 3">已撤销</el-tag>
          <el-tag type="warning" v-else-if="row.status === 4">驳回待修改</el-tag>
          <el-tag type="info" v-else-if="row.status === 5">修改待审批</el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="status"
          label="结果"
          align="center"
          width="120"
      >
        <template #default="{row}">
          <el-tag type="warning" v-if="row.result === 0">拒绝</el-tag>
          <el-tag type="success" v-else-if="row.result === 1">通过</el-tag>
          <el-tag type="info" v-else>进行中</el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="operatorName"
          label="当前/最后审批人"
          align="center"
          width="150"
      />
      <el-table-column
          label="理由/说明/备注"
          width="400"
          align="center"
      >
        <template #default="{row}">
          {{ row.content}}
        </template>
      </el-table-column>
      <el-table-column
          label="操作"
          align="center"
      >
        <template #default="{row}">
          <el-button
              type="primary"
              size="small"
              @click="showDetails(row.approve_id)"
          >
            审批记录
          </el-button>
          <el-button
              v-if="row.file"
              @click="previewFile(row)"
          >
            附件预览
          </el-button>
          <el-button
              v-if="row.file"
              @click="downloadFile(row.approve_id,row.uploaderName,row.file)"
          >
            下载附件
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <RreViewDialog ref="preRef"  @refreshGoing='getList'/>

  <EditFormDialog ref="editDialogRef"  @refreshEdit="getList"/>
</template>

<script setup>
import {ElButton, ElTable, ElTableColumn, ElTag} from "element-plus"
import RreViewDialog from "@/components/Common/OA/Seal/PreviewSealDialog.vue"
import {delSealApprove, getMyGoingSealApprove, returnSealById} from "@/api/OA/Seal"
import {onMounted, ref} from "vue"
import {computeDate, createMsg, getUserInfo, isPDF, processSealFileJSON} from "@/lib/utils"
import {useRoute, useRouter} from "vue-router"
import emitter from "@/lib/eventBus"
import EditFormDialog from "@/components/Common/OA/Seal/EditForm.vue"
import {download, getCompleteApprove} from "@/api/OA/Approve"
import {previewYRL} from "@/api/http"

const route = useRoute()
const router = useRouter()

let preRef = ref()
let editDialogRef = ref()
let userInfo = {}
const tableData = ref([])

onMounted(()=>{
  emitter.emit('updateMySeal','/mine-complete')
  if (route.path !== '/mine-complete') router.push('/mine-complete')
  userInfo = getUserInfo()
  getList()
})

const getList = async () => {
  try {
    const {data:res} = await getCompleteApprove(userInfo.id)
    if (res.code === 200){
      tableData.value = res.data
    } else if (res.code === 201){
      // createMsg('暂无数据','info',true)
    } else if (res.code === 400 ||res.code === 401 ||res.code === 402){
      createMsg('未查询到数据','info',true)
    }
  } catch (e) {
    console.log(e)
  }
}

const showDetails = (id) => {
  preRef.value.showDetails(id)
}


const returnSeal = async (id) => {
  try {
    const {data:res} = await returnSealById(id)
    if (res.code === 200){
      await getApproveList()
      createMsg('操作成功!','success',true)
    } else if (res.code === 201){
      createMsg(res.data,'success',true)
    } else {
      return createMsg('操作失败','warning',false)
    }
  } catch (e) {
    console.log(e)
  }
}

const delDetails = async (id,status) => {
  try {
    if(status === 2){
      return createMsg('已完成的流程不能撤銷!','error','false')
    }
    const res = window.confirm('撤销后该流程无法恢复,确认操作吗?')
    if (res){
      const {data:res} = await delSealApprove(id,userInfo.id)
      if (res.code === 200){
        await getList                                                                                                               ()
        return createMsg('操作成功!','success',true)
      } else if (res.code === 201){
        return createMsg(res.data,'info',true)
      } else {
        return createMsg(res.data,'warning',true)
      }
    }
  } catch (e) {
    console.log(e)
  }
}


const previewFile = async (row) => {
  if (!isPDF(row)) return createMsg('仅pdf文件支持在线预览','info',true)
  await window.open(`${previewYRL}/previewS?approveId=${row.approve_id}`)
}

const downloadFile = async (id,uploaderName,file) => {
  try {
    const res = await download(id)
    const type = processSealFileJSON(file)
    // 创建一个新的 URL 对象，并生成一个下载链接
    const url = window.URL.createObjectURL(new Blob([res.data],
        { type: type.type }));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `${uploaderName}的流程附件.${type.ext}`); // 设置下载的文件名
    link.style.display = 'none' // 隐藏元素
    document.body.appendChild(link);
    link.click()
    // 清理 DOM 和释放 URL 对象
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (e) {
    console.log(e)
  }
}

</script>

<style scoped lang="less">
.flow-box{
  width: 99%;
  margin: 0 auto;
}
</style>
